import { DownOutlined, EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import { Button, Dropdown, Form, Input, Select, Space, Tag, message, Modal, Tree } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { businessReportList } from '@/services/api/gng';
import { useAccess, Access } from 'umi';
import { request } from 'umi';
import EditCom from './edit';
import { handleTreeList } from '@/utils'
import ConfCom from './pz';
import './index.less'
const { Option } = Select;
export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};

type businessReportItem = {
  id: string;
  url: string | undefined;
  reportName: string;
};

export default (props: any) => {
  const requestsUrls = {
    // list: "/sys/menu/?sourceType=WEB",
    list: "/sys/menu/?sourceType=",
    delete: "/sys/menu/",
  };
  const actionRef = useRef<ActionType>();
  const editRef = useRef();
  const confRef = useRef();
  const access = useAccess();
  const [form] = Form.useForm(); //搜索表单
  // const pageAuth = access[props.route.key] || {edit:true,delete:true,add:true};
  const pageAuth = { edit: true, delete: true, add: true };//权限暂时写死
  const deleteFn = (id) => {
    Modal.confirm({
      title: '确认删除？',
      content: '',
      onOk() {

        request(requestsUrls.delete + id, {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json',
          },
          data: {
            id
          }
        }).then((res) => {
          message.success(res?.meta?.msg);
          actionRef.current?.reload();
        })
      },
      onCancel() {
        console.log('Cancel')
      }
    })
  }
  const columns: ProColumns<businessReportItem>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
      title: '序号',
    },
    {
      title: '卡片名称',
      align: "center",
      key: 'title',
      dataIndex: 'title',
      hideInSearch: true,
    },
    {
      title: '卡片适用设备端',
      align: "center",
      key: 'sourceType',
      dataIndex: 'sourceType',
      hideInSearch: true,
    },
    {
      title: '描述',
      align: "center",
      key: 'remark',
      dataIndex: 'remark',
      // hideInSearch: true,
    },
  ];
  // const columns: ProColumns<businessReportItem>[] = [
  //   {
  //     title: '页面名称',
  //     key: 'menuName',
  //     dataIndex: 'menuName',
  //     hideInSearch: true,
  //   },
  //   {
  //     title: '操作',
  //     key: 'scan',
  //     dataIndex: 'scan',
  //     width: "180px",
  //     hideInSearch: true,
  //     render: (txt, record, index) => {
  //       return <>
  //         <a
  //           key="editable"
  //           onClick={() => {
  //             confRef.current?.init(record.menuId, record);
  //           }}
  //         >
  //           配置
  //         </a>
  //       </>

  //     }
  //   }
  // ];
  const [selectKey, setselectKey] = useState([]);
  const [menusTree, setmenusTree] = useState(null);
  const getMenus = async () => {
    const response: any = await request('/sys/menu/?sourceType=APP', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {

      },
    });
    let data = handleTreeList(response?.data)
    setmenusTree(data)
  }
  useEffect(() => {
    getMenus()
  }, [])

  useEffect(() => {
    if (selectKey) {
      actionRef.current?.reload();
    }

  }, [selectKey]);
  return (
    <>
      <div className='indexPage'>
        <div className='indexLeft'>
          {/* <Menu
                    onClick={(e) => {
                        setselectKey(e.key);
                    }}
                    selectedKeys={selectKey}
                >
                    {businessTypedata.map((item: any, i: number) => {
                        return (
                            <Menu.Item key={item.value}>
                                <div>
                                    <span style={{ marginLeft: '10px' }}>{item.name}</span>
                                </div>
                            </Menu.Item>
                        );
                    })}
                </Menu> */}
          {
            menusTree && <Tree
              switcherIcon={<DownOutlined />}
              defaultExpandedKeys={['0-0-0']}
              onSelect={(selectedKeys) => {
                if (selectedKeys.length > 0) {
                  setselectKey(selectedKeys)
                }
                console.log(selectedKeys)
              }}
              selectedKeys={selectKey}
              fieldNames={{ title: 'menuName', key: 'menuId' }}
              treeData={menusTree}
            />
          }

        </div>
        <div className='indexRight'>
          {
            selectKey.length > 0 &&

            <ProTable
              actionRef={actionRef}
              columns={columns}
              pagination={false}
              search={false}
              rowKey={record => record?.menuId}
              params={form.getFieldsValue()}
              // params 是需要自带的参数
              // 这个参数优先级更高，会覆盖查询表单的参数
              request={async (
                // 第一个参数 params 查询表单和 params 参数的结合
                // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
                params: T & {
                  pageSize: number;
                  //current: number;
                },
                sort,
                filter,
              ) => {
                // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
                // 如果需要转化参数可以在这里进行修改
                const bussType = selectKey.length > 0 ? selectKey[0] : '';
                const response: any = await request('/sys/group/' + bussType + '/menu', {
                  method: 'GET',
                  headers: {
                    'Content-Type': 'application/json',
                  },
                  data: {
                    ...params,

                  },
                });
                let data = response?.data
                return {
                  data: data,
                  // success 请返回 true，
                  // 不然 table 会停止解析数据，即使有数据
                  success: true,
                  // 不传会使用 data 的长度，如果是分页一定要传
                  total: response?.data?.totalCount,
                  //message.success(res?.meta?.msg);
                };
              }}
              toolBarRender={() => [
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    const bussType = selectKey.length > 0 ? selectKey[0] : '';
                    confRef.current?.init(bussType)
                  }}
                  type="primary"
                >
                  分配
                </Button>
              ]}
            // 

            />
          }
          <EditCom
            ref={editRef}
            bussType={selectKey.length > 0 ? selectKey[0] : ''}
            callback={() => {
              actionRef.current?.reload();
            }}
          />
          <ConfCom
            ref={confRef}
            bussType={selectKey.length > 0 ? selectKey[0] : ''}
            callback={() => {
              actionRef.current?.reload();
            }}
          />
        </div>
      </div>


    </>
  );
};
